package movieGandalf.dbParser;

import java.io.BufferedReader;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import movieGandalf.database.MovieTools;

public class GenresAdder implements DataReader{
	
	public int read(Connection conn, BufferedReader in){
		String line = null;
		
		PreparedStatement stmt = null;
		
		String imdbName = null;
		BigInteger movieID = null;
		String genre = null;
		Integer genreID = null;
		
		try {
			boolean isBegin = true;

			stmt = conn.prepareStatement("REPLACE INTO MovieGenres (movieID,genreID) VALUES(?,?)");
			
			while ((line = in.readLine()) != null){
				
				int len = line.length();
				
				if (isBegin){
					if ((line.length()<15 || !line.subSequence(len-15, len).equals("THE GENRES LIST")))
						continue;
					else{
						isBegin = false;
						line = in.readLine();
						continue;
					}
				}
				
				if (len<=0 || line.charAt(0)=='"')
					continue;
				
				int i = 0;
				for (i = line.length()-1;i>=0;i--){
					if (line.charAt(i)=='\t'){
						i++;
						break;
					}
				}
				
				if (i<=0)
					continue;
				
				genre = line.substring(i, len);
				if (!MovieTools.genreValidator(genre))
					continue;
				
				genreID = MovieTools.getGenreID(conn, genre);
				if (genreID == null)
					continue;
				
				imdbName = ParserTools.getIMDBName(line);
				if (!MovieTools.movieValidator(imdbName))
					continue;
				
				movieID = MovieTools.getMovieID(conn, imdbName);
				if (movieID == null)
					continue;
				
				stmt.setObject(1, movieID);
				stmt.setObject(2, genreID);
				stmt.addBatch();
			}

			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try{
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}